import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form, Select, Input, Button, Upload, Icon  } from 'antd';
const Option = Select.Option;
@connect(({up}) => ({
    cate:up.cate,
  }))
  
class Up extends PureComponent {
 
    state = {
      loading: false
    };

    componentDidMount() {
        const { dispatch } = this.props;
        dispatch({
          type: 'up/cate',
        }); 
    } 
    getBase64(img, callback) {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result));
        reader.readAsDataURL(img);
      }
      handleChange = (info) => {
        if (info.file.status === 'uploading') {
          this.setState({ loading: true });
          return;
        }
        if (info.file.status === 'done') {
          this.setState({
            loading: false,
          });
        }
      }
    beforeUpload(file){
        this.getBase64(file, (imageUrl) =>
          {
            this.setState({
              imageUrl,
              loading: false
            })
            if(imageUrl){
              let apirul = '/myApi/wallpaper_uploads/';
              let u = imageUrl.substring(imageUrl.indexOf(',') + 1, imageUrl.length)
              let data = {
                image_name:file.name,
                image_data:u
              }
              fetch(apirul,{
                method: 'post',
                headers: {
                  "Content-Type": "application/json"
                },
                body: JSON.stringify(data),
              })
              .then(res => res.json())
              .then(res => {
                this.setState({pic_url:res.pic_url});
              })
            }
          });
        return 1;
      }

    handleSubmit = (e) => {
        let apirul = '/myApi/wallpaper_uploads_confirm/';
        //接口地址
        let data = {
          name:this.props.form.getFieldsValue().name,
          category:this.props.form.getFieldsValue().category,
          pic_url:this.state.pic_url
        }
        fetch(apirul,{
          method: 'post',
          headers: {
            "Content-Type": "application/json"
          },
          body: JSON.stringify(data),
        })
        .then(function (res) {
          return res.json();
        })
        .then(res => {
          console.log(res);
        })
      }
    render() {
        //获取数据接口里的分类数据
        const { cate } = this.props;
        const children = [];
        for (let i = 0; i < cate.length; i++) {
            children.push(<Option key={i} value={ cate[i]}>{ cate[i] }</Option>);
        }
 
        const FormItem = Form.Item;
        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 14 },
        };
 
        const uploadButton = (
            <div>
              <Icon type={this.state.loading ? 'loading' : 'plus'} />
              <div className="ant-upload-text">Upload</div>
            </div>
        );
        const imageUrl = this.state.imageUrl;
        const { getFieldProps } = this.props.form;
        return (
            <Form onSubmit={this.handleSubmit} >
                <FormItem
                {...formItemLayout}
                label="图片名称"
                >
                    <Input {...getFieldProps('name')} placeholder="Please input name" style={{ width:"300px" }} />
                </FormItem>
                <FormItem
                {...formItemLayout}
                label="图片类型"
                >
                    <Select {...getFieldProps('category')} placeholder="Please select a category" style={{ width:"300px" }} >
                        {children}
                    </Select>
                </FormItem>
                <FormItem
                {...formItemLayout}
                label="上传图片"
                >
                  <Upload
                    {...getFieldProps('pic_url')}
                    listType="picture-card"
                    className="avatar-uploader"
                    showUploadList={false}
                    action=""
                    beforeUpload={this.beforeUpload.bind(this)}
                    onChange={this.handleChange}
                  >
                    {imageUrl ? <img src={imageUrl} alt="avatar" /> : uploadButton}
 
                  </Upload>
                </FormItem>
                <FormItem
                wrapperCol={{ span: 12, offset: 6 }}
                >
                  <Button type="primary" htmlType="submit">提交</Button>
                </FormItem>
            </Form>
        );
    }
}
//Form.create()方法是将this.props.form填进来，使能获取用户输入的值
const UpForm = Form.create()(Up);
export default UpForm;